package com.example.logistics.service;

import com.example.logistics.controller.dto.CreateShipmentRequest;
import com.example.logistics.entity.*;
import com.example.logistics.repository.CarrierRepository;
import com.example.logistics.repository.CustomerOrderRepository;
import com.example.logistics.repository.ShipmentRepository;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.OffsetDateTime;

@Service
@RequiredArgsConstructor
public class ShipmentService {
    private final ShipmentRepository shipmentRepository;
    private final CustomerOrderRepository orderRepository;
    private final CarrierRepository carrierRepository;

    @Transactional
    public Shipment createShipment(CreateShipmentRequest request) {
        CustomerOrder order = orderRepository.findById(request.getOrderId())
                .orElseThrow(() -> new EntityNotFoundException("Order not found"));
        Carrier carrier = carrierRepository.findById(request.getCarrierId())
                .orElseThrow(() -> new EntityNotFoundException("Carrier not found"));

        Shipment shipment = Shipment.builder()
                .trackingNumber(request.getTrackingNumber())
                .status(ShipmentStatus.CREATED)
                .order(order)
                .carrier(carrier)
                .shippedAt(OffsetDateTime.now())
                .build();

        order.setStatus(OrderStatus.SHIPPED);
        order.setUpdatedAt(OffsetDateTime.now());

        return shipmentRepository.save(shipment);
    }

    @Transactional
    public Shipment updateStatus(Long shipmentId, ShipmentStatus status) {
        Shipment shipment = shipmentRepository.findById(shipmentId)
                .orElseThrow(() -> new EntityNotFoundException("Shipment not found"));
        shipment.setStatus(status);
        if (status == ShipmentStatus.DELIVERED) {
            shipment.setDeliveredAt(OffsetDateTime.now());
            shipment.getOrder().setStatus(OrderStatus.DELIVERED);
        }
        return shipmentRepository.save(shipment);
    }
}


